package cn.lastcc.pwdmanage.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.lastcc.pwdmanage.R;
import cn.lastcc.pwdmanage.core.AesUtil;
import cn.lastcc.pwdmanage.core.CustomApp;
import cn.lastcc.pwdmanage.core.SerialUtil;
import cn.lastcc.pwdmanage.entity.Info;
import cn.lastcc.pwdmanage.entity.PwdTag;

public class PwdListActivity extends Activity {

    // 选中的 ListView ID
    private String pwdListSelectId = "";

    // 声明控件
    private ListView lvPwd = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("密码列表");
        setContentView(R.layout.activity_pwd_list);
        // Show the Up button in the action bar.
//        setupActionBar();
        refreshPwdList(); // 展示密码 ListView
    }

    /**
     * 刷新密码 ListView
     *
     * @author Added by baidongyang 2013-6-29
     */
    private void refreshPwdList() {
        // 根据 ID 获取控件对象
        this.lvPwd = (ListView) this.findViewById(R.id.lvPwd_pla);
        Info info = null;
        try {
            info = SerialUtil.getInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != info) {
            CustomApp customApp = (CustomApp) this.getApplication();
            List<Map<String, String>> tagList = new ArrayList<Map<String,String>>();
            List<PwdTag> pwdTagList = info.getPwdTagList();
            byte [] logonPwdBytes = AesUtil.decrypt(AesUtil.parseHexStr2Byte(customApp.getUserPwd()), customApp.getEncpwd());
            final String logonPwd = new String(logonPwdBytes);
            for (int i = 0, j = pwdTagList.size(); i < j; i++) {
                PwdTag pwdTag = pwdTagList.get(i);
                Map<String, String> item = new HashMap<String, String>();
                byte [] decryptResult = AesUtil.decrypt(AesUtil.parseHexStr2Byte(pwdTag.getTagName()), logonPwd);
                final String __decTag = new String(decryptResult);
//                Log.d("bxDebug", "__decTag: " + __decTag);
                item.put("ItemId",pwdTag.getId());
                item.put("ItemTitle", __decTag);
                tagList.add(item);
            }
            // 创建适配器
            SimpleAdapter adapter = new SimpleAdapter(this, tagList, R.layout.listview_pwd_list, new String [] {"ItemId","ItemTitle"}, new int [] {R.id.lblItemId_pla, R.id.lblItemTitle_pla});
            this.lvPwd.setAdapter(adapter);
            this.lvPwd.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                // 创建长按菜单
                @Override
                public void onCreateContextMenu(ContextMenu menu, View v,
                        ContextMenuInfo menuInfo) {
                    menu.add(0, 4, 0, "查看");
                    menu.add(0, 0, 1, "编辑");
                    menu.add(0, 1, 2, "删除");
                    menu.add(0, 2, 3, "删除全部");
                    menu.add(0, 3, 4, "取消");
                }
            });
            this.lvPwd.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                /*
                 * 点击列表项时触发onItemClick方法，四个参数含义分别为
                 * arg0：发生单击事件的AdapterView
                 * view：AdapterView中被点击的View
                 * position：当前点击的行在adapter的下标
                 * id：当前点击的行的id
                 */
                @Override
                public void onItemClick(AdapterView<?> arg0, View view,
                        int arg2, long arg3) {
                    TextView lblItemTitle_pla = (TextView) view.findViewById(R.id.lblItemId_pla);
                    pwdListSelectId = lblItemTitle_pla.getText().toString();
                    lvPwd.showContextMenu();
                }
            });
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
        case 0: // 编辑
        	// 启动创建密码窗口(CreatePwdActivity)
            Intent createPwdIntent = new Intent();
            createPwdIntent.setClass(PwdListActivity.this, CreatePwdActivity.class);
            Bundle bundle=new Bundle();
            bundle.putString("fromClassName", "PwdListActivity");
            bundle.putString("pwdTagId", pwdListSelectId);
            createPwdIntent.putExtras(bundle);
            startActivity(createPwdIntent);
            break;
        case 1: // 删除
            // 弹出确认对话框
            AlertDialog.Builder deleteConfirm = new AlertDialog.Builder(PwdListActivity.this);
            deleteConfirm.setTitle(R.string.str_userPwdModifyActivity_removePwd_confirmTitle);
            deleteConfirm.setMessage(R.string.msg_userPwdModifyActivity_removePwd_confirm);
            // 确认按钮单击事件
            deleteConfirm.setPositiveButton(R.string.str_globe_OK, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int msgId = PwdListActivity.this.removePwdTag(pwdListSelectId);
                    Toast.makeText(PwdListActivity.this.getApplicationContext(), msgId, Toast.LENGTH_SHORT).show();
                    // 删除成功，刷新视图
                    if (msgId == R.string.msg_userPwdModifyActivity_removePwd_success) {
                        PwdListActivity.this.refreshPwdList();
                    }
                }
            });
            // 取消按钮单击事件
            deleteConfirm.setNegativeButton(R.string.str_globe_Cancel, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            deleteConfirm.create().show();
            break;
        case 2: // 删除全部
            // 弹出确认对话框
            AlertDialog.Builder deleteAllConfirm = new AlertDialog.Builder(PwdListActivity.this);
            deleteAllConfirm.setTitle(R.string.str_userPwdModifyActivity_removePwd_confirmTitle);
            deleteAllConfirm.setMessage(R.string.msg_userPwdModifyActivity_removePwd_confirmAll);
            // 确认按钮单击事件
            deleteAllConfirm.setPositiveButton(R.string.str_globe_OK, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int msgId = PwdListActivity.this.removePwdTag(null);
                    Toast.makeText(PwdListActivity.this.getApplicationContext(), msgId, Toast.LENGTH_SHORT).show();
                    // 删除成功，刷新视图
                    if (msgId == R.string.msg_userPwdModifyActivity_removePwd_success) {
                        PwdListActivity.this.refreshPwdList();
                    }
                }
            });
            // 取消按钮单击事件
            deleteAllConfirm.setNegativeButton(R.string.str_globe_Cancel, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            deleteAllConfirm.create().show();
            break;
        case 4: // 查看
            // 弹出提示对话框
            AlertDialog.Builder showPwdConfirm = new AlertDialog.Builder(PwdListActivity.this);
            showPwdConfirm.setTitle(R.string.msg_userPwdModifyActivity_showPwdConfirmTitle);
            showPwdConfirm.setMessage(R.string.msg_userPwdModifyActivity_showPwdConfirmContent);
            // 确认按钮单击事件
            showPwdConfirm.setPositiveButton(R.string.str_globe_Yes, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    AlertDialog.Builder showPwdDialog = new AlertDialog.Builder(PwdListActivity.this);
                    Info info = null;
                    try {
                        info = SerialUtil.getInfo();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(PwdListActivity.this, R.string.msg_userPwdModifyActivity_showPwdFailed, Toast.LENGTH_SHORT);
                        return;
                    }
                    CustomApp customApp = (CustomApp) PwdListActivity.this.getApplication();
                    byte [] logonPwdBytes = AesUtil.decrypt(AesUtil.parseHexStr2Byte(customApp.getUserPwd()), customApp.getEncpwd());
                    final String logonPwd = new String(logonPwdBytes);
                    List<PwdTag> pwdTagList = info.getPwdTagList();
                    String tagName = "";
                    String pwd = "";
                    for (int i = 0, j = pwdTagList.size(); i < j; i++) {
                        PwdTag pwdTag = pwdTagList.get(i);
                        if (pwdListSelectId.equals(pwdTag.getId())) {
                            // 解密标签
                            String __tagName = pwdTag.getTagName();
                            byte [] tagNameBytes = AesUtil.decrypt(AesUtil.parseHexStr2Byte(__tagName), logonPwd);
                            tagName = new String(tagNameBytes);
                            // 解密密码
                            String __pwd = pwdTag.getPwd();
                            byte [] pwdBytes = AesUtil.decrypt(AesUtil.parseHexStr2Byte(__pwd), logonPwd);
                            pwd = new String(pwdBytes);
                            break;
                        }
                    }
                    showPwdDialog.setTitle(tagName);
                    showPwdDialog.setMessage(pwd);
                    showPwdDialog.setPositiveButton(R.string.str_globe_OK, new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    showPwdDialog.create().show();
                }
            });
            // 取消按钮单击事件
            showPwdConfirm.setNegativeButton(R.string.str_globe_No, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            showPwdConfirm.create().show();
            break;
        default: break;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 删除密码
     * @param pwdTagId ListView 中选中的密码对象 id，即需要删除的对象 ID；<br/>
     * 如果需要删除全部已保存的密码，传入 null 即可。
     * @return 消息句柄，即对应的 R.string.msg id 号
     * @author Added by baidongyang 2013-6-30
     */
    private int removePwdTag (String pwdTagId) {
        int resultMsgId = -1;
        Info info = null;
        try {
            info = SerialUtil.getInfo();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            resultMsgId = R.string.msg_userPwdModifyActivity_removePwd_readFileNotFind;
        } catch (IOException e) {
            e.printStackTrace();
            resultMsgId = R.string.msg_userPwdModifyActivity_removePwd_readIoException;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            resultMsgId = R.string.msg_userPwdModifyActivity_removePwd_readClassNotFind;
        }
        if (resultMsgId >= 0) {
            return resultMsgId;
        }
        if (null == info) {
            return R.string.msg_userPwdModifyActivity_removePwd_readInfoIsNull;
        }
        List<PwdTag> pwdTagList = null;
        if ((null == pwdTagId) || ("".equals(pwdTagId))) {
            pwdTagList = new ArrayList<PwdTag>();
        } else {
            pwdTagList = info.getPwdTagList();
            for (int i = 0, j = pwdTagList.size(); i < j; i++) {
                PwdTag pwdTag = pwdTagList.get(i);
                if (pwdTagId.equals(pwdTag.getId())) {
                    pwdTagList.remove(i);
                    break;
                }
            }
        }
        info.setPwdTagList(pwdTagList);
        try {
            SerialUtil.setInfo(info);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            resultMsgId = R.string.msg_userPwdModifyActivity_removePwd_writeFileNotFind;
        } catch (IOException e) {
            e.printStackTrace();
            resultMsgId = R.string.msg_userPwdModifyActivity_removePwd_writeIoException;
        }
        resultMsgId = R.string.msg_userPwdModifyActivity_removePwd_success;
        return resultMsgId;
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.pwd_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case R.id.muitAddPwd_pla:
            Bundle bundle=new Bundle();
            bundle.putString("fromClassName", "PwdListActivity");
            Intent intent = new Intent();
            intent.setClass(this, CreatePwdActivity.class);
            intent.putExtras(bundle);
            this.startActivity(intent);
            break;
        case R.id.muitRefresh_pla:
            this.refreshPwdList();
            Toast.makeText(this.getApplicationContext(), R.string.msg_userPwdModifyActivity_muitRefreshSuccess, Toast.LENGTH_SHORT).show();
            break;
        default :
//            Log.d("bx", "默认的菜单被选中: " + item.getItemId());
            break;
        }
        return super.onOptionsItemSelected(item);
    }

}
